package org.dizena.utils;

import org.apache.commons.lang3.StringUtils;
import org.dizena.base.avo.req.JqGridReq;
import org.dizena.base.avo.resp.JqGridResp;
import org.dizena.base.dao.DbDao;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JqGridRespBuilder<T>
{

    public JqGridResp<T> build(JqGridReq req, DbDao<T> dao)
    {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(req.getSearchField()) && StringUtils.isNotEmpty(req.getSearchString()))
        {
            params.put(req.getSearchField(), req.getSearchString());
        }
        List<T> list = dao.queryAll(req, params);
        Long count = dao.count(req.getSearchField(), params);
        Long tmp = count / req.getRows();
        Long pages = count % req.getRows() == 0 ? tmp : tmp + 1;
        JqGridResp<T> result = new JqGridResp<>();
        result.setCode(200);
        result.setMsg("ok");
        result.setRows(list);
        result.setTotal(pages);
        result.setPage(req.getPage());
        result.setRecords(count);
        return result;
    }

    public JqGridResp<T> build(JqGridReq req, DbDao<T> dao, String[] keys, Object[] values)
    {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(req.getSearchField()) && StringUtils.isNotEmpty(req.getSearchString()))
        {
            params.put(req.getSearchField(), req.getSearchString());
        }
        if (keys != null && keys.length > 0 && keys.length == values.length)
        {
            for (int i = 0; i < keys.length; i++)
            {
                params.put(keys[i], values[i]);
            }
        }
        List<T> list = dao.queryAll(req, params);
        Long count = dao.count(req.getSearchField(), params);
        Long tmp = count / req.getRows();
        Long pages = count % req.getRows() == 0 ? tmp : tmp + 1;
        JqGridResp<T> result = new JqGridResp<>();
        result.setCode(200);
        result.setMsg("ok");
        result.setRows(list);
        result.setTotal(pages);
        result.setPage(req.getPage());
        result.setRecords(count);
        return result;
    }

}
